package com.fanketly.funacg2.data.repo

import android.util.Log
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.dto.LoginDTO
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.network.RetrofitNetwork
import com.fanketly.funacg2.data.network.flowResult
import com.fanketly.funacg2.utils.ToastUtils
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.singleOrNull
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AudioRepo @Inject constructor(
    private val network: RetrofitNetwork,
) {

    suspend fun isExpires() = network.isExpires()
    suspend fun getAuth(username: String, password: String) =
        flowResult { emit(network.getAuth(LoginDTO(username, password))) }

    suspend fun register(username: String, password: String) =
        flowResult { emit(network.register(LoginDTO(username, password))) }

    /**
     * 获取音声列表
     * */

    suspend fun getRecommend() =network.getRecommend()

    suspend fun getWorkList(page: Int, pageSize: Int, order: String, sort: String): WorkList {
        val workList = flow {
            emit(
                network.getWorkList(
                    page,
                    pageSize,
                    order,
                    sort
                )
            )
        }.catch {
            Log.i(TAG, "getWorkList: ${it.localizedMessage}")
            ToastUtils.shortToast("获取ASMR失败，${it.localizedMessage}")
            emit(WorkList())
        }.singleOrNull() ?: WorkList()

//        if (App.sIsAllAges) {
//            return workList.copy(works = workList.works.filter { !it.nsfw })
//        }
        return workList
    }


    /**
     * 获取音声
     * */
    suspend fun getAudio(id: Int) = network.getAudio(id)

    /**
     *获取分类
     * */
    suspend fun getTags() = flowResult { emit(network.getTags()) }

    /**
     * 获取分类音声
     * */
    suspend fun getWorkListByTag(tag: Int, page: Int, pageSize: Int): WorkList {
        val workList = network.getWorkListByTag(tag, page, pageSize)
//        if (App.sIsAllAges) {
//            return workList.copy(works = workList.works.filter { !it.nsfw })
//        }
        return workList
    }

    /**
     * 获取搜索音声
     * */
    suspend fun getWorkListBySearch(name: String, page: Int, pageSize: Int): WorkList {
        val workList = network.getWorkListBySearch(name, page, pageSize)
//        if (App.sIsAllAges) {
//            return workList.copy(works = workList.works.filter { !it.nsfw })
//        }
        return workList
    }
}